global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/build_bhj_data.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"
capture noi {


qui do ${code_dir}/config/country_list.do

* ----------------------------------------
* ----------------------------------------
* Prepare BHJ exercise datasets
* ----------------------------------------
* ----------------------------------------


* 1) Build a long dataset of exposure shares (BvD-country-year level)
* ----------------------------------------

* baseline
*get firms and the lseid ised in xtset
use BvD lse_id using ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear 
duplicates drop

*keep if in the regression sample
mmerge BvD using ${final_dir}/bvd_list_regfirms_auto95.dta, unmatched(master)
keep if _m == 3

* get the patent weights and save long
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
keep lse_id share2_all*
duplicates drop
reshape long share2_all_1995_, i(lse_id) j(country, string)
ren share2_all_1995_ s_n
save ${dataset_dir}/bhj/lseid_ctryweights_long.dta, replace

*expand them to the year set
expand 15
bysort lse_id country: gen year = 1994 + _n
gen s_nt = s_n / 15
drop s_n
save ${dataset_dir}/bhj/lseid_year_ctryweights_long.dta, replace

* foreign only, normalized to 1
use BvD lse_id country_shr_1995 using ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear 
duplicates drop
mmerge BvD using ${final_dir}/bvd_list_regfirms_auto95.dta, unmatched(master)
keep if _m == 3 
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
keep lse_id share2_all*

*get the homecountry share and construct the weights of all other countries
egen maxshare = rowmax(share2_all_1995_??)
gen foreign_share = 1 - maxshare
foreach ctry of global countrylist1995 {
				*if the firm is only in one country, the foreign share is 0
				replace share2_all_1995_`ctry' = 0 if maxshare == share2_all_1995_`ctry'
}
foreach ctry of global countrylist1995 {
				*if its in more that one country, normalize the shares using the foreign as denominator
				replace share2_all_1995_`ctry' = share2_all_1995_`ctry' / foreign_share
}

keep lse_id share2_all*
duplicates drop
reshape long share2_all_1995_, i(lse_id) j(country, string)
ren share2_all_1995_ s_n

save ${dataset_dir}/bhj/lseid_ctryweights_long_foreign.dta, replace

*expand to yearly
expand 15
bysort lse_id country: gen year = 1994 + _n
gen s_nt = s_n / 15
drop s_n
save ${dataset_dir}/bhj/lseid_year_ctryweights_long_foreign.dta, replace


*using patent weights computed across a smaller set of countries for longterm interest rate
use BvD lse_id using ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear 
mmerge BvD using ${final_dir}/bvd_list_regfirms_auto95.dta, unmatched(master)
keep if _m == 3
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_forLintr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
keep lse_id share2_all*
duplicates drop
reshape long share2_all_1995_, i(lse_id) j(country, string)
ren share2_all_1995_ s_n
save ${dataset_dir}/bhj/lseid_ctryweights_long_forlintr.dta, replace

*expand to yearly set
expand 15
bysort lse_id country: gen year = 1994 + _n
gen s_nt = s_n / 15
drop s_n
save ${dataset_dir}/bhj/lseid_year_ctryweights_long_forlintr.dta, replace


* 2) Add further controls, redefine spillovers, define avg log variables
* ---------------------------------------------------------------------

* Build spillovers in terms of usual country weights 
*load the countrystocks for the spillovers and reshape wide
use ${dataset_dir}/spillovers/ctry_inventions_stocks.dta, clear
keep year invt_country kbia_auto95 kbia_N_auto95
foreach pt of varlist k* {
		ren `pt' `pt'_
	}
reshape wide k*, i(year) j(invt_country) string
compress
tempfile invt_stocks_auto95_wide
save `invt_stocks_auto95_wide', replace


*load our firms
use ${dataset_dir}/dep_vars/bvd_year_list_from1970_tfacit1.dta, clear

* Get (baseline) weights
mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
drop _m
*use gdp as backup
cross using ${dataset_dir}/weights/shares_GDP_allctries_1995.dta
sort BvD year

foreach ctry of global countrylist1995 {
	*set a country s weight to the patent weight and use GDP if not present
	gen weight_`ctry' = share2_all_1995_`ctry'
	replace weight_`ctry' = share_GDP_`ctry' if weight_`ctry' == .
}

* Get country-level invention stocks, build avg of log
mmerge year using `invt_stocks_auto95_wide', unmatched(master)
sort BvD year
foreach vv in auto95 N_auto95 {
    foreach ctry in $invtcountrylist {
		*check if countryweight exists, set to zero if not
        noisily capture confirm variable weight_`ctry'
        if _rc != 0 {
            gen weight_`ctry' = 0
        }
		*make the avg of the log
        gen lnkbia`vv'_wtd_`ctry' = weight_`ctry' * log(kbia_`vv'_`ctry') 
        replace lnkbia`vv'_wtd_`ctry' = 0 if kbia_`vv'_`ctry' == 0 
    }
}

*get the collected values
foreach vv in auto95 N_auto95 {
    egen lnspill_`vv'_bia_1995_wtd = rowtotal(lnkbia`vv'_wtd_??), missing
}

*rename and make indicator for for zero values
rename lnspill_auto95_bia_1995_wtd lnspillauto95bia_1995_acw
rename lnspill_N_auto95_bia_1995_wtd lnspillNauto95bia_1995_acw
gen lnspillauto95bia_1995_acw0 = lnspillauto95bia_1995_acw ==0
gen lnspillNauto95bia_1995_acw0 = lnspillNauto95bia_1995_acw ==0

keep BvD year lnspillauto95bia_1995_acw* lnspillNauto95bia_1995_acw*

save ${dataset_dir}/bhj/bhj_bvd_year_spillovers.dta, replace


* Build recent innovations as avg of log
*load the firms and their homecountry and its share
use ${dataset_dir}/indep_vars/bvd_year_country_multinational_from1970_tfacit1.dta, clear
keep BvD country_shr_1995
bys BvD : gen x = _n
keep if x == 1
drop x
compress
tempfile maxweight
save `maxweight', replace

*load our patent weights
use ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, clear
tempfile wtfacit1
save `wtfacit1'

*load our inventorweights
use ${dataset_dir}/weights/bvdid_inventor_weights_all_from1970_1995_orbis2017.dta, clear
foreach ctry of global invtcountrylist {
	ren share_invt_1995_`ctry' share2_all_1995_`ctry'
}
tempfile wiw
save `wiw'


global clist_iw $invtcountrylist 
global clist_tfacit1 $countrylist1995
global clist ${clist_${wtype}}

* SPILLOVERS auto95 variables (weighted using patents since 1970)

*load the firms
use ${dataset_dir}/dep_vars/bvd_year_list${weight_window}_${wtype}.dta, clear

* Add country-level invention stocks
mmerge year using ${dataset_dir}/spillovers/ctry_auth_stocks_wide_bia_recent_innovation.dta, unmatched(master) ukeep(kbia_auto95* kbia_N_auto95*)
mmerge BvD using `maxweight', unmatched(master)
mmerge BvD using `w${wtype}', unmatched(master) 
gen missing_dspill_weights_1995=(_m==1)
drop _m

*get avergae shares of the authorities as backup
cross using ${dataset_dir}/weights/shares_auth_allctries_alltechs_1995.dta
gen dshare = .
foreach ctry of global clist{
	*check if variable exists and set to zero otherwise
	noisily capture confirm variable share_WD_total_inv_`ctry'
	if _rc != 0 {
		gen share_WD_total_inv_`ctry' = 0
	}
	*set the weights and averages if no weight
	gen weight_`ctry' = share2_all_1995_`ctry'
	replace weight_`ctry' = share_WD_total_inv_`ctry' if weight_`ctry' == .
	replace dshare = weight_`ctry' if country_shr_1995 =="`ctry'"
}

*check if we have a stock for the country
sort BvD year
foreach vv in auto95 N_auto95 {
	foreach ctry in $clist {
		noisily capture confirm variable kbia_`vv'_`ctry'
		if _rc != 0 {
			gen kbia_`vv'_`ctry' = 0
		}
		*make weighted log values
		gen lnkbia`vv'_wtd_`ctry' = weight_`ctry' * log(kbia_`vv'_`ctry')
           replace lnkbia`vv'_wtd_`ctry' = 0 if kbia_`vv'_`ctry' == 0
	}
}

*collect all for a firm
foreach vv in auto95 N_auto95 {
	egen lndspill_`vv'_1995_wtd = rowtotal(lnkbia`vv'_wtd_??), missing
}

*set indicator for zero values
gen lndspill_auto95_1995_0 = lndspill_auto95_1995_wtd == 0
gen lndspill_N_auto95_1995_0 = lndspill_N_auto95_1995_wtd == 0

keep BvD year lndspill_auto95_1995_wtd lndspill_N_auto95_1995_wtd lndspill_auto95_1995_0 lndspill_N_auto95_1995_0
compress

save ${dataset_dir}/bhj/bhj_bvd_year_recent_innovations.dta, replace


* Build lintr in terms of non-adjusted "baseline" weights, just for manufacturing and our main deflator
*load firms and interest rate
use ${dataset_dir}/dep_vars/bvd_year_list_from1970_tfacit1.dta, clear
keep BvD year
mmerge year using ${dataset_dir}/indep_vars/interestrates_wide_MANUF.dta, unmatched(none)

	*laod the patent weights
	mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
	drop _m
	*load GDP as backup
	cross using ${dataset_dir}/weights/shares_GDP_allctries_1995.dta
	sort BvD year
	foreach vv in lintrMP {
		foreach ctry of global countrylist1995 {
			*check if variable exists and set to missing otherwise
			noisily capture confirm variable `vv'_`ctry'
			if _rc != 0 {
				gen `vv'_`ctry' = .
			}

			*set weights
			gen weight_`ctry' = share2_all_1995_`ctry'
			replace weight_`ctry' = share_GDP_`ctry' if weight_`ctry' == .
			
			*set weighted values and weighted log values
			gen `vv'_itd_`ctry' = weight_`ctry'* `vv'_`ctry'
			gen ln`vv'_itd_`ctry' = weight_`ctry'* ln(`vv'_`ctry')
		}
		*get all observations per firm and sum them up
		egen `vv'_ALL_1995_wtd = rowtotal(`vv'_itd_??), missing
		egen ln`vv'_ALL_1995_wtd = rowtotal(ln`vv'_itd_??), missing		
	}
    keep BvD year lnlintrMP_ALL_1995_wtd

	*labeling

compress
save ${dataset_dir}/bhj/bhj_bvd_year_lintr.dta, replace


* 3) Merge into and define variables to run ssaggregate on
* ---------------------------------------------------------------------

use ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear

* Subset regression data to regfirms and set correct time structure for depvar
mmerge BvD using ${final_dir}/bvd_list_regfirms_auto95.dta, unmatched(master)
keep if _m == 3
xtset lse_id year

*generate the avg of logs
gen arcsinh_${depvar}_${ttt} = ln(${depvar}_${ttt}+((${depvar}_${ttt})^2+1)^(1/2))
replace ${depvar}_${ttt} = F2.${depvar}_${ttt}
replace arcsinh_${depvar}_${ttt} = F2.arcsinh_${depvar}_${ttt}
keep if year >= 1995 & year <= 2009

* add the spilovers and the additional controls
mmerge BvD year using ${final_dir}/bvd_year_offshoring_sharesgdpweighted_from1970_tfacit1.dta, unmatched(master)
mmerge BvD year using ${dataset_dir}/spillovers/bvd_year_dspillovers_auto95_bia_tfacit1_recent_innovation.dta, unmatched(master)
mmerge BvD year using ${dataset_dir}/bhj/bhj_bvd_year_spillovers.dta, unmatched(master)
mmerge BvD year using ${dataset_dir}/bhj/bhj_bvd_year_recent_innovations.dta, unmatched(master)
mmerge BvD year using ${dataset_dir}/bhj/bhj_bvd_year_lintr.dta, unmatched(master)

* Define the LHS variables. NOTE: We use the average of logs so that for instance g_n = lnLSW!! 
clonevar LSW = lnlswMPm_1995_a
clonevar HSW = lnhswMPm_1995_a
clonevar GDPGAP = lngdpgap_1995_a

* hotfix for labor productivity because there is an error above: (it wasn't a avg of logs to begin with)
clonevar VAEMP = lnvaempMPm_1995_a 
mmerge BvD year using ${dataset_dir}/indep_vars/bvd_year_wages_vaemp_manuf_sharesgdpweighted_from1970_tfacit1.dta, ukeep(lnvaempMPm_ALL_1995_wtd) unmatched(master)
replace VAEMP = lnvaempMPm_ALL_1995_wtd
clonevar GDPPC = lngdppcMPm_1995_a

gen ISP = LSW - HSW

clonevar stockown = k${depvar}_${ttt} 
clonevar stockownzero = k${depvar}_${ttt}0
clonevar stockother = kNOT_${depvar}_${ttt} 
clonevar stockotherzero = kNOT_${depvar}_${ttt}0	
clonevar spilloversown = lnspill${depvar}${ttt}_1995_acw
clonevar spilloversother = lnspillN${depvar}${ttt}_1995_acw
clonevar spilloversownzero = lnspill${depvar}${ttt}_1995_acw0
clonevar spilloversotherzero = lnspillN${depvar}${ttt}_1995_acw0

clonevar spilloversown_og = spill${depvar}${ttt}_1995_a
clonevar spilloversother_og = spillN${depvar}${ttt}_1995_a
clonevar spilloversownzero_og = spill${depvar}${ttt}_1995_a0 
clonevar spilloversotherzero_og = spillN${depvar}${ttt}_1995_a0

local stocks stockown stockownzero stockother stockotherzero
local spillovers spilloversown spilloversother spilloversownzero spilloversotherzero
local spillovers_og spilloversown_og spilloversother_og spilloversownzero_og spilloversotherzero_og

* Define additional control variables
clonevar spilloversownpw = lndspill_${depvar}_1995_wtd
clonevar spilloversotherpw = lndspill_N_${depvar}_1995_wtd
clonevar spilloversownzeropw = lndspill_${depvar}_1995_0 
clonevar spilloversotherzeropw = lndspill_N_${depvar}_1995_0 
clonevar offshoring = offshoring_ALL_1995_wtd
clonevar mshare = msharem_1995_a
clonevar manufsize = lnmVAm_1995_a
clonevar mds_control = mVAlsm_1995_a
local recent_innov spilloversownpw spilloversotherpw spilloversownzeropw spilloversotherzeropw
clonevar lintr = lnlintrMP_ALL_1995_wtd

* Create FE indicators
tab year, gen(YY_)
egen yearctry = group(year country_shr_1995) if year <= 2009
egen yearindustry = group(year industry) if year <= 2009
egen yearctryindustry = group(year industry country_shr_1995) if year <= 2009
sort lse_id year

* Save firm level data
keep BvD year *${depvar}_${ttt}* lse_id ISP LSW HSW VAEMP GDPGAP GDPPC `stocks' `spillovers'  `spillovers_og' `recent_innov' offshoring manufsize mshare mds_control lintr country_shr_1995 yearctry yearindustry yearctryindustry missing_weights_1995 missing_spill_weights_1995 maxweight_1995
save ${final_dir}/regression_dataset_from1970_tfacit1_avglog.dta, replace


* 4) Build a dataset with all country-level information 
* -----------------------------------------------------

* get all macro country-year level data
use year gdppcMP_?? using ${dataset_dir}/indep_vars/gdp_percapita_wide_MANUF.dta, clear
mmerge year using ${dataset_dir}/indep_vars/loggdp_gap_wide_MANUF.dta, unmatched(none) ukeep(year lngdpgap_??) 
mmerge year using ${dataset_dir}/indep_vars/lswages_wide_MANUF.dta, unmatched(none) ukeep(year lswMP_??)
mmerge year using ${dataset_dir}/indep_vars/hswages_wide_MANUF.dta, unmatched(none) ukeep(year hswMP_??)
mmerge year using ${dataset_dir}/indep_vars/vaemployee_wide_MANUF.dta, unmatched(none) ukeep(year vaempMP_??)
mmerge year using ${dataset_dir}/indep_vars/manufshare_wide_MANUF.dta, unmatched(none) ukeep(year mshare_??)
mmerge year using ${dataset_dir}/indep_vars/manufVA_wide_MANUF.dta, unmatched(none) ukeep(year mVA_??)
mmerge year using ${dataset_dir}/import/offshoring_data.dta, unmatched(none) ukeep(year offshoring_??)
mmerge year using ${dataset_dir}/spillovers/ctry_auth_stocks_wide_bia_recent_innovation.dta, unmatched(none) ukeep(year kbia_auto95_?? kbia_N_auto95_??)
mmerge year using ${dataset_dir}/indep_vars/interestrates_wide_MANUF.dta, unmatched(none) ukeep(year lintrMP_??)
drop _m

* reshape long, clean up
keep if year >= 1995 & year <= 2009
reshape long lswMP_ hswMP_ vaempMP_ gdppcMP_ lngdpgap_ mshare_ mVA_ offshoring_ lintrMP_ kbia_auto95_ kbia_N_auto95_, i(year) j(country, string)

foreach v in lsw hsw vaemp gdppc lintr {
	ren `v'MP `v'
	ren `v' , upper
}

ren mVA MANUFSIZE
ren (mshare offshoring lngdpgap kbia_auto95 kbia_N_auto95) (gMSHARE gOFFSHORING gGDPGAP gSPILLOVERSOWNPW gSPILLOVERSOTHERPW)

* take logs
ds, has(type numeric)
local varlist `r(varlist)'
local exclude year gGDPGAP gMSHARE gOFFSHORING gSPILLOVERSOWNPW gSPILLOVERSOTHERPW
local ln_vars : list varlist - exclude
foreach var of local ln_vars {
    gen g`var' =ln(`var')
}
replace gSPILLOVERSOWNPW = log(gSPILLOVERSOWNPW)
replace gSPILLOVERSOWNPW = 0 if gSPILLOVERSOWN == .
replace gSPILLOVERSOTHERPW = log(gSPILLOVERSOTHERPW)
replace gSPILLOVERSOTHERPW = 0 if gSPILLOVERSOTHERPW == .
tempfile ctry_year_macro
save `ctry_year_macro', replace

* get country level invention stocks
use ${dataset_dir}/spillovers/ctry_inventions_stocks.dta, clear
keep year invt_country kbia_auto95 kbia_N_auto95 
rename invt_country country
gen gSPILLOVERSOWN =log(kbia_auto95)
replace gSPILLOVERSOWN = 0 if gSPILLOVERSOWN == .
gen gSPILLOVERSOTHER = log(kbia_N_auto95)
replace gSPILLOVERSOTHER = 0 if gSPILLOVERSOTHER == .
tempfile ctry_year_invention_stocks
save `ctry_year_invention_stocks', replace

use `ctry_year_macro', clear
mmerge country year using `ctry_year_invention_stocks', unmatched(master)
drop _m

* oecd indiciator and lsw bins
xtile bin3_lsw = LSW, n(3)
xtile bin5_lsw = LSW, n(5)
gen oecd = 0
foreach ctry of global countrylist_oecd { 
    replace oecd = 1 if country == "`ctry'"
}
* ISP
gen gISP = gLSW - gHSW
gen ISP = LSW / HSW

* cleanup names
ren (LSW HSW VAEMP GDPPC MANUFSIZE LINTR ISP) (LSW_level HSW_level VAEMP_level GDPPC_level MANUFSIZE_level LINTR_level ISP_level)
save ${dataset_dir}/bhj/country_year_macrovariables.dta, replace

* 5) Aggregate to country-level equivalence, residualize on different specficiations
* ----------------------------------------------------------------------------------

use ${final_dir}/regression_dataset_from1970_tfacit1_avglog.dta, clear

local F lse_id
local F_IY lse_id yearindustry
local F_IY_CY lse_id yearindustry yearctry
local IY yearindustry
local CY yearctry
local IY_CY yearindustry yearctry
local stocks stockown stockownzero stockother stockotherzero
local spillovers spilloversown spilloversownzero spilloversother spilloversotherzero

local ct1
local fe1

local ct2 HSW
local fe2 

local ct3 HSW
local fe3 `F'

local ct4 HSW
local fe4 `F_IY'

local ct5 HSW
local fe5 `F_IY_CY'

local ct6
local fe6 `F'

local ct7 
local fe7 `F_IY'

local ct8 
local fe8 `F_IY_CY'

local ct9
local fe9 `IY'

local ct10
local fe10 `CY'

local ct11
local fe11 `IY_CY'

local ct12 `spillovers' `stocks'
local fe12 `F_IY'

local ct13 `spillovers' `stocks'
local fe13 `F_IY_CY'


*create shock level aggregates
ssaggregate LSW HSW arcsinh_auto95_bia, ///
	n(country) t(year) s(s_n) sfilename(${dataset_dir}/bhj/lseid_year_ctryweights_long) l(lse_id) ///
	controls("`ct1'" "`ct2'" "`ct3'" "`ct4'" "`ct5'" "`ct6'" "`ct7'" "`ct8'" "`ct9'" "`ct10'" "`ct11'" "`ct12'" "`ct13'") ///
	absorb("`fe1'" "`fe2'" "`fe3'" "`fe4'" "`fe5'" "`fe6'" "`fe7'" "`fe8'" "`fe9'" "`fe10'" "`fe11'" "`fe12'" "`fe13'")
mmerge country year using ${dataset_dir}/bhj/country_year_macrovariables, unmatched(master) 
drop _m

ren (LSW1 LSW2 LSW3 LSW4 LSW5 LSW6 LSW7 LSW8 LSW9 LSW10 LSW11 LSW12 LSW13) (rLSW rLSW_hsw rLSW_hsw_f rLSW_hsw_f_iy rLSW_hsw_fiycy rLSW_f rLSW_fiy rLSW_fiycy rLSW_iycy rLSW_iy rLSW_cy rLSW_ssfiy rLSW_ssfiycy)
ren (HSW1 HSW2 HSW3 HSW4 HSW5 HSW6 HSW7 HSW8 HSW9 HSW10 HSW11 HSW12 HSW13) (rHSW rHSW_hsw rHSW_hsw_f rHSW_hsw_f_iy rHSW_hsw_fiycy rHSW_f rHSW_fiy rHSW_fiycy rHSW_iycy rHSW_iy rHSW_cy rHSW_ssfiy rHSW_ssfiycy)
ren (arcsinh_auto95_bia1 arcsinh_auto95_bia2 arcsinh_auto95_bia3 arcsinh_auto95_bia4 arcsinh_auto95_bia5 arcsinh_auto95_bia6 arcsinh_auto95_bia7 arcsinh_auto95_bia8 arcsinh_auto95_bia9 arcsinh_auto95_bia10 arcsinh_auto95_bia11 arcsinh_auto95_bia12 arcsinh_auto95_bia13) (arcsinh_auto95_bia rarcsinh_auto95_bia_hsw rarcsinh_auto95_bia_hsw_f rarcsinh_auto95_bia_hsw_f_iy rarcsinh_auto95_bia_hsw_fiycy rarcsinh_auto95_bia_f rarcsinh_auto95_bia_fiy rarcsinh_auto95_bia_fiycy rarcsinh_auto95_bia_iycy rarcsinh_auto95_bia_iy rarcsinh_auto95_bia_cy rarcsinh_auto95_bia_ssfiy rarcsinh_auto95_bia_ssfiycy)

local vars1 _f _fiy _fiycy _iycy _iy _cy _ssfiy _ssfiycy
foreach v of local vars1 {
	gen rISP`v' = rLSW`v' - rHSW`v'
}
replace LSW = gLSW
replace HSW = gHSW
gen ISP = LSW - HSW
keep country year `depvar' r`depvar'* ISP LSW HSW rISP* rLSW* rHSW* s_n

mmerge country year using ${dataset_dir}/bhj/country_year_macrovariables.dta, unmatched(master)
drop _m
egen country_id = group(country)
xtset country_id year 
save ${final_dir}/regression_dataset_from1970_tfacit1_countrylevel_resid.dta, replace

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat